package com.jeeplus.itemInterface.frontInterface;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.*;
import com.jeeplus.modules.customerservice.entity.CustomerService;
import com.jeeplus.modules.customerservice.service.CustomerServiceService;
import com.jeeplus.modules.lunbo.entity.Lunbo;
import com.jeeplus.modules.lunbo.service.LunboService;
import com.jeeplus.modules.tradetimes.entity.TradeTimes;
import com.jeeplus.modules.tradetimes.service.TradeTimesService;
import com.jeeplus.modules.ver.entity.Ver;
import com.jeeplus.modules.ver.service.VerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(value = "FrontInterfaceController", description = "页面信息")
@Controller
@RequestMapping(value = "${frontPath}/account")
public class FrontInterfaceController {

	@Autowired
	private OssConfig ossConfig;
	@Autowired
	private FileStorageService fileStorageService;
	@Autowired
	private VerService verService;
	@Autowired
	private LunboService lunboService;
	@Autowired
	private TradeTimesService tradeTimesService;
	@Autowired
	private CustomerServiceService customerServiceService;
	
	

	/*
	 * 阿里云oss配置
	 */
//	public static String ENDPOINT = "http://oss-cn-qingdao.aliyuncs.com";
//	public static String ACCESSKEYID = "LTAI4GECxViwuWBwFQKrpx2A";
//	public static String ACCESSKEYSECRET = "BPXSLxxDBVpQDA9fDxkDzJpcJKy5dT";
//	public static String BUCKETNAME = "pintuanw";
//	public static String KEY = "images/";

	public static String ENDPOINT = "oss-cn-qingdao.aliyuncs.com";
	public static String BUCKETNAME = "pintuanw";
	public static String ACCESSKEYID = "LTAI4GECxViwuWBwFQKrpx2A";
	public static String ACCESSKEYSECRET = "BPXSLxxDBVpQDA9fDxkDzJpcJKy5dT";
	public static String SUFFERURL = "http://pintuanw.oss-cn-qingdao.aliyuncs.com/";
	public static String EXPROJECTNAME = "ptw";

	
	
	@ResponseBody
    @GetMapping("getVer")
    @ApiOperation(value = "获取当前最新版本号",notes = "获取当前最新版本号")
    public AjaxJson getVer(HttpServletRequest request,HttpServletResponse response) {
    	AjaxJson aj = new AjaxJson();
    	List<Ver> list = verService.findList(new Ver());
    	if(list.size()>0) {
    		aj.setSuccess(true);
    		aj.setMsg("获取成功");
    		aj.put("ver", list.get(0).getVer());
    	}else {
			aj.setSuccess(false);
			aj.setMsg("无版本号");
		}
    	return aj;
    }
	
	
	
	@ResponseBody
	@PostMapping("/uploadImg")
	@ApiOperation(value = "上传图片", notes = "上传图片")
	public AjaxJson uploadImg(@RequestParam("fileData") MultipartFile multipartFile) throws Exception {
		AjaxJson aj = new AjaxJson();
		try {
			String path = ossConfig.getServerPath();
			// 处理上传文件
			String name = multipartFile.getOriginalFilename();
			String suffix = name.substring(name.lastIndexOf(".") == -1 ? name.length() : name.lastIndexOf("."));// 后缀
			String osn = IdGen.uuid().toUpperCase() + suffix;// uuid+后缀作为文件名
			// 保存
			fileStorageService.save(osn, multipartFile.getInputStream());
			aj.put("path", path + osn);
			aj.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			aj.setSuccess(false);
			aj.setMsg("系统错误！");
		}
		return aj;
	}

	/**
	 * 阿里云短信验证码
	 * 
	 * @param req
	 * @param res
	 * @param
	 * @return
	 */
	@ResponseBody
	@PostMapping("aliSendSms")
	@ApiOperation(value = "阿里云短信验证码", notes = "阿里云短信验证码")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "mobile", value = "手机号", dataType = "String", paramType = "query", required = true) })
	public AjaxJson aliSendSms(HttpServletRequest req, HttpServletResponse res) {
		AjaxJson aj = new AjaxJson();
		int random = (int) ((Math.random() * 9 + 1) * 100000);
		String mobile = req.getParameter("mobile");
		System.out.println("验证码：" + random);

		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GBsxJCchLSKEN33XPZo",
				"quhGMi2z8Cf5pxZhUKqVUydbRi3GqR");
		IAcsClient client = new DefaultAcsClient(profile);
		CommonRequest request = new CommonRequest();
		request.setSysMethod(MethodType.POST);
		request.setSysDomain("dysmsapi.aliyuncs.com");
		request.setSysVersion("2017-05-25");
		request.setSysAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		request.putQueryParameter("PhoneNumbers", mobile);
		request.putQueryParameter("SignName", "人参庄园");
		request.putQueryParameter("TemplateCode", "SMS_201790147");
		request.putQueryParameter("TemplateParam", "{\"code\":\"" + random + "\"}");
		try {
			CommonResponse response = client.getCommonResponse(request);
			System.out.println(response.getData());
			JSONObject object = JSONObject.fromObject(response.getData());
			if ("OK".equals(object.get("Code"))) {
				System.out.println(object.get("Message"));
				aj.setSuccess(true);
				aj.put("code", random + "");
				aj.setMsg(object.get("Message").toString());
			} else {
				System.out.println(object.get("Message").toString());
				aj.setSuccess(false);
			}
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return aj;
	}


	@ResponseBody
	@GetMapping("/getRotationPic")
	@ApiOperation(value = "获取轮播图", notes = "获取轮播图")
	public AjaxJson getRotationPic() {
		AjaxJson aj = new AjaxJson();
		List<Lunbo> list = new ArrayList<>();
		Lunbo lunbo = new Lunbo();
		lunbo.setLunbo("0");
		List<Lunbo> lunboList = lunboService.findList(lunbo);
		if (lunboList.size()>0){
			list.addAll(lunboList);
		}
		aj.put("rotation",list);
		aj.setSuccess(true);
		aj.setMsg("获取成功");
		return aj;
	}


	@ResponseBody
	@GetMapping("/isTradingRange")
	@ApiOperation(value = "是否交易时间", notes = "是否交易时间")
	public AjaxJson isTradingRange() throws ParseException{
		AjaxJson aj = new AjaxJson();
		List<TradeTimes> tradeTimesList = tradeTimesService.findList(new TradeTimes());
		boolean flag = false;
		boolean flag1 = false;
		if (tradeTimesList.size()>0){
			for (TradeTimes tradeTimes : tradeTimesList) {


					if (StringUtils.isNotBlank(tradeTimes.getTradeWeek())){
						String[] weeks = tradeTimes.getTradeWeek().split(",");

						SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
						Date nowTime =df.parse(df.format(new Date()));
						//规定时间
						Date beginTime = df.parse(tradeTimes.getStartTime());
						Date endTime = df.parse(tradeTimes.getEndTime());
						//调用判断方法是否在规定时间段内
						boolean isTime = DateUtils.timeCalendar(nowTime, beginTime, endTime);
						if (isTime && Arrays.asList(weeks).contains(getWeekStr())){
							if ("0".equals(tradeTimes.getIsTrade())){
								flag = true;
								break;
							}
						}
//						else {
//							aj.setSuccess(false);
//							aj.setMsg("非交易时间");
//							return aj;
//						}
					}

			}
			if (!flag){
				aj.setSuccess(false);
				aj.setMsg("交易关闭");
				return aj;
			}
//			if ("0".equals(tradeTimesList.get(0).getIsTrade())){
//				if (StringUtils.isNotBlank(tradeTimesList.get(0).getTradeWeek())){
//					String[] weeks = tradeTimesList.get(0).getTradeWeek().split(",");
//
//					SimpleDateFormat df = new SimpleDateFormat("HH:mm");//设置日期格式
//					Date nowTime =df.parse(df.format(new Date()));
//					//规定时间
//					Date beginTime = df.parse(tradeTimesList.get(0).getStartTime());
//					Date endTime = df.parse(tradeTimesList.get(0).getEndTime());
//					//调用判断方法是否在规定时间段内
//					boolean isTime = DateUtils.timeCalendar(nowTime, beginTime, endTime);
//					if (isTime && Arrays.asList(weeks).contains(getWeekStr())){
//						aj.setSuccess(true);
//					}else {
//						aj.setSuccess(false);
//						aj.setMsg("交易开放时间为每周"+tradeTimesList.get(0).getTradeWeek()+","+tradeTimesList.get(0).getStartTime()+"至"+tradeTimesList.get(0).getEndTime());
//						return aj;
//					}
//				}
//			}else {
//				aj.setMsg("交易关闭");
//				aj.setSuccess(false);
//				return aj;
//			}
		}
		aj.setSuccess(true);
		return aj;
	}


	public static String getWeekStr() {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		int week  = cal.get(Calendar.DAY_OF_WEEK);
		switch (week) {
			case 1:
				return "7";
			case 2:
				return "1";
			case 3:
				return "2";
			case 4:
				return "3";
			case 5:
				return "4";
			case 6:
				return "5";
			case 7:
				return "6";
			default:
				return "";
		}
	}


	@ResponseBody
	@GetMapping("/getCustomer")
	@ApiOperation(value = "获取客服信息", notes = "获取客服信息")
	public AjaxJson getCustomer() {
		AjaxJson aj = new AjaxJson();
		List<CustomerService> list = customerServiceService.findList(new CustomerService());
		aj.put("customer",list.size()>0?list.get(0):"");
		aj.setSuccess(true);
		aj.setMsg("获取成功");
		return aj;
	}

	
}
